package com.zhiyou100.action;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhiyou100.entity.House;
import com.zhiyou100.service.HouseService;
import com.zhiyou100.util.object.ObjectUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 房屋 action
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-08-28 15:27
 */
@Controller
@RequestMapping("/house")
public class HouseAction {
    private HouseService houseService;

    @Autowired
    public void setHouseService(HouseService houseService) {
        this.houseService = houseService;
    }


    /**
     * 分页查询
     *
     * @param model  放域属性
     * @param pageNo 请求的页数
     * @return view/house/list
     */
    @RequestMapping("/list.action")
    public String listHouses(Model model,
                             @RequestParam(defaultValue = "1", value = "pageNo") Integer pageNo
    ) {
        // 每页显示的记录数
        int pageSize = 10;

        // 分页查询
        PageHelper.startPage(pageNo, pageSize);

        // 获取所有的信息
        final List<House> list = houseService.listHouse();

        // 使用 PageInfo<Source> 结果进行封装
        final PageInfo<House> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo", pageInfo);
        return "view/house/list";
    }

    /**
     * 根据 hid 获取一个
     *
     * @return java.lang.String
     * @param: [hid, method, model]
     */
    @RequestMapping("/getOneByHid.action")
    public String getOneByHid(Integer hid, String method, Model model) {
        final House house = houseService.selectOneByHid(hid);
        if (house != null) {
            // 有，放入区域中，跳转 到 详情页面
            if (method == null || method.trim().length() == 0) {
                // 跳转到 view/house/detail
                model.addAttribute("house", house);
                return "view/house/detail";
            } else {
                // 跳转到更新界面
                model.addAttribute("house", house);
                return "view/house/update";
            }

        } else {
            // 没有，返回列表
            return "view/house/list";
        }
    }

    /**
     * 更新一条记录
     *
     * @return java.lang.String
     * @param: [hid, harea, hcommunity, hunitnumber, hfloor, hroomno, hacreage, hdirection, hfitment, hisdoubleair, hlimit, hfacility, hprice, hstatus, himg, haddress, request]
     */
    @SneakyThrows
    @RequestMapping("/updateOneByHid.action")
    public String updateOneByHid(Integer hid,
                                 String harea,
                                 String hcommunity,
                                 String hunitnumber,
                                 Integer hfloor,
                                 String hroomno,
                                 String hacreage,
                                 Integer hdirection,
                                 Integer hfitment,
                                 Integer hisdoubleair,
                                 Integer hlimit,
                                 String hfacility,
                                 Float hprice,
                                 Integer hstatus,
                                 @RequestParam("himg") CommonsMultipartFile himg,
                                 String haddress,
                                 HttpServletRequest request
    ) {
        final House house = House.builder()
                .hid(hid)
                .harea(harea)
                .hcommunity(hcommunity)
                .hunitnumber(hunitnumber)
                .hfloor(hfloor)
                .hroomno(hroomno)
                .hacreage(hacreage)
                .hdirection(hdirection)
                .hfitment(hfitment)
                .hisdoubleair(hisdoubleair)
                .hfitment(hfitment)
                .hlimit(hlimit)
                .hfacility(hfacility)
                .hprice(hprice)
                .hstatus(hstatus)
                .haddress(haddress)
                .build();

        // House(hid=1002, harea=二七区, hcommunity=升龙国际, hunitnumber=五单元, hfloor=20, hroomno=2002, hacreage=100, hdirection=1, hfitment=1, hisdoubleair=1, hlimit=3, hfacility=空调-wife-电视, hprice=30.0, hstatus=1, himg=, haddress=河南-郑州-二七区-升龙国际-a区5号楼五单元2002, haddtime=null, hupdatetime=Fri Aug 28 00:22:28 CST 2020)

        uploadFile(house, himg, request);
        // 设置修改时间为当前时间
        house.setHupdatetime(new Date());


        // 更新一条数据
        houseService.updateOneHouse(house);
        return "/view/house/list";
    }

    /**
     * 自定义一个 日期属性编辑器
     * yyyy-MM-dd'T'HH:mm:ss 针对 <input type="datetime-local" value="2020-08-28T20:49:16">
     *
     * @param request HttpServletRequest
     * @param binder  binder
     */
    @InitBinder
    public void myDateBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }

    /**
     * 根据 hid 删除一个用户
     *
     * @param hid 要删除的 id
     * @return /view/house/list
     */
    @RequestMapping("/deleteOneByHid.action")
    public String deleteOneByHid(Integer hid) {
        if (hid != null) {
            houseService.deleteOneByHid(hid);
        }
        return "/view/house/list";
    }

    /**
     * 插入一条记录
     *
     * @param house   实体类
     * @param img     图片
     * @param request 域属性
     * @return /view/house/list
     */
    @SneakyThrows
    @RequestMapping("/insertOne.action")
    public String insertOne(House house, @RequestParam("img") CommonsMultipartFile img, HttpServletRequest request) {
        String id = "hid";
        String haddtime = "haddtime";
        String hupdatetime = "hupdatetime";
        String himg = "himg";
        if (ObjectUtil.onlyOneFiledIsNullAndTheFiledIsId(house, id, haddtime, hupdatetime, himg)) {
            // 只有 hid haddtime  hupdatetime 字段为 null,，合法，继续
            uploadFile(house, img, request);
            // 设置添加时间
            house.setHaddtime(new Date());
            // 设置修改时间为当前时间
            house.setHupdatetime(new Date());
            // 插入一条数据
            houseService.insertOne(house);
        }
        return "/view/house/list";
    }

    /**
     * 判断文件是否为空，如果不为空，添加到 image 中，修改文件名，放到数据库
     *
     * @param house   实体类
     * @param img     文件
     * @param request request
     * @throws IOException 可能文件不存在
     */
    private void uploadFile(House house, @RequestParam("img") CommonsMultipartFile img, HttpServletRequest request) throws IOException {
        if (!img.isEmpty()) {
            // 有文件，上传
            // 上传的文件保存的位置
            final String path = request.getServletContext().getRealPath("image");
            final File realPath = new File(path);

            // 防止文件名重复，加上毫秒值
            final String fileName = System.currentTimeMillis() + img.getOriginalFilename();
            // 设置放入数据库的文件名
            house.setHimg(fileName);

            // 最终的图片地址
            final File finalPath = new File(realPath, fileName);

            // 直接写文件
            img.transferTo(finalPath);
        }
    }

}
